<template>
  <el-dialog 
    title="批量导入题库" 
    :visible.sync="dialogVisible" 
    width="60%" 
    @close="handleClose"
    custom-class="custom-dialog"
    :close-on-click-modal="false">
    
 <el-form :model="formData" label-width="100px" class="file-upload-container">
      <!-- <el-form-item label="解析" prop="content">
        <el-input
          type="textarea"
          :rows="10"
          v-model="formData.content"
          placeholder="请输入内容"
          style="width: 100%"
        />
      </el-form-item> -->
      <el-form-item label="题目分类" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择题目分类" style="width: 100%">
          <el-option
            v-for="item in questionCategories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="上传文件" prop="file">
        <el-upload
          class="upload-demo"
          action="#"
          :on-change="handleFileChange"
          :on-remove="handleRemove"
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
          :http-request="addHandler">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            支持 excel 格式文件，文件大小不超过 10MB
          </div>
        </el-upload>
      </el-form-item>
      
      <el-form-item>
        <el-button type="text" @click="downloadTemplate">
          <i class="el-icon-download"></i> 下载导入模板
        </el-button>
      </el-form-item>
    </el-form>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel" icon="el-icon-close">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        icon="el-icon-upload" 
        :disabled="!canSubmit"
        :loading="loading">
        开始导入
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import SessionManager from '@/utils/sessionManager.js'
export default {
  name: 'BatchImportDialog',
  props: {
    questionCategories: {
      type: Array,
      default: () => []
    },
    categoryId: {
      type: Number,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      formData: {
        content: '',
        categoryId: this.categoryId,
        file: null
      },
      fileList: [],
      questionCategories: [],
    }
  },
  
  created() {
    console.log('BatchImportDialog created')
  },

  computed: {
    canSubmit() {
      return this.formData.content.trim() !== '' || (this.fileList && this.fileList.length > 0)
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal
    }
  },
  methods: {
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1) // 只保留最后一个文件
      this.formData.file = file.raw
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.formData.file = null
    },
    handleExceed() {
      this.$message.warning('每次只能上传一个文件')
    },
    addHandler() {
      // 自定义上传方法
    },
    downloadTemplate() {
      console.log('开始下载模板文件...');
      // 使用 axios 实例
      this.$http({
        url: '/questionFile/template/download',
        method: 'GET',
        responseType: 'blob' // 确保正确处理二进制数据
            }).then(response => {
        // 获取文件名
       const contentDisposition = response.headers['content-disposition'];
       let filename = 'template.xlsx';
       if (contentDisposition) {
        const matches = contentDisposition.match(/filename="(.+)"/);
        if (matches && matches[1]) {
          filename = matches[1];
        }
      }
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    
    // 清理
    window.URL.revokeObjectURL(url);
    link.remove();
    
    // 显示成功提示
    this.$message.success('模板下载成功');
      }).catch(error => {
    // 错误处理
    console.error('下载模板失败:', error);
    this.$message.error('下载模板失败，请稍后重试');
      });
    },
    handleSubmit() {
      console.log('开始上传文件...');
      console.log('文件:', this.fileList[0].raw);
      console.log('教师ID:', SessionManager.getUserId());
      this.loading = true;
      const formData = new FormData();
      formData.append('file', this.fileList[0].raw); // 添加文件，使用 raw 属性获取文件对象
      formData.append('teacherId', SessionManager.getUserId());
      formData.append('categoryId', this.formData.categoryId);
      
      this.$http.post('/questionFile/upload', formData).then(res => {
        if (res.data && res.data.code === 200) {
          this.$message.success('上传成功');
        } else {
          this.$message.error(res.data && res.data.message ? res.data.message : '上传失败');
        }
      }).catch(error => {
        console.error('上传失败:', error);
        this.$message.error('上传失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleClose() {
      this.fileList = []
      this.formData = {
        content: '',
        file: null
      }
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.upload-demo {
  width: 100%;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>
